from django.db.models import FileField, signals
from django.dispatch import dispatcher
from django.conf import settings
import os

class AutoFileField(FileField):
    def _save(self, instance=None, **kwargs):
	if getattr(instance, self.name):
            filename = getattr(instance, self.name).path
            ext = os.path.splitext(filename)[1].lower()
            dst = self.generate_filename(instance, '%s_%s%s' % (self.name, instance._get_pk_val(), ext))
            dst_fullpath = os.path.join(settings.MEDIA_ROOT, dst)
            if os.path.abspath(filename) != os.path.abspath(dst_fullpath):
                os.rename(filename, dst_fullpath)
                setattr(instance, self.attname, dst)
                instance.save()
           
    def contribute_to_class(self, cls, name):
        super(AutoFileField, self).contribute_to_class(cls, name)
	signals.post_save.connect(self._save, sender=cls)
    
    def get_internal_type(self):
        return 'FileField'

